﻿using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using RIABlog.Web;
using RIABlog.Web.Models;

namespace RIABlog
{
	public partial class BlogPostCtl : UserControl
	{
        /// <summary>
        /// Доступно ли добавление комментариев
        /// </summary>
        public Visibility AddCommentVisibility
        {
            get { return (Visibility)GetValue(AddCommentVisibilityProperty); }
            set { SetValue(AddCommentVisibilityProperty, value); }
        }

        /// <summary>
        /// Identifies the AddCommentVisibility dependency property.
        /// </summary>
        public static readonly DependencyProperty AddCommentVisibilityProperty = DependencyProperty.Register(
            "AddCommentVisibility",
            typeof(Visibility),
            typeof(BlogPostCtl),
            new PropertyMetadata(Visibility.Collapsed, AddCommentVisibilityChanged));

        /// <summary>
        /// AddCommentVisibilityProperty property changed handler.
        /// </summary>
        private static void AddCommentVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BlogPostCtl) d).panelAddComment.Visibility = (Visibility)e.NewValue;
        }

        /// <summary>
        /// Ссылка на экземпляр приложения
        /// </summary>
        protected App App
        {
            get { return (App)Application.Current; }
        }

        /// <summary>
        /// Ссылка на экземпляр контекста доступа к данным
        /// </summary>
        protected RIABlogContext BlogContext
        {
            get { return this.App.BlogContext; }
        }

		public BlogPostCtl()
		{
			// Required to initialize variables
			InitializeComponent();
		}

        private void AddCommentButton_Click(object sender, RoutedEventArgs e)
        {
			if(string.IsNullOrEmpty(this.txtComment.Text))
			{
				return;
			}

            var blogPost = (BlogPost) this.DataContext;

            var newComment = new Comment
                {
                    PostId = blogPost.Id,
                    Text = this.txtComment.Text
                };

            // добавляем комментарий
            blogPost.Comments.Add(newComment);

            // сразу сохраняем изменения
            this.BlogContext.SubmitChanges(this.SubmitChangesCompleted, null);

            this.txtComment.Text = string.Empty;
        }

        private void SubmitChangesCompleted(SubmitOperation op)
        {
            if (op.HasError)
            {
                // если произошла ошибка - отменяем изменения
                this.BlogContext.RejectChanges();
            }
        }
	}
}